package com.dh.example.io.server;


import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.dh.example.io.handler.HeartBeatHandler;
import com.dh.example.io.manager.SocketClientManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * netty套接字io服务器
 *
 * @author yolo
 * @date 2024/03/06 19:07:44
 */
@Component
@Slf4j
public class NettySocketIoServer implements InitializingBean, DisposableBean {

    @Resource
    private SocketIOServer socketIoServer;

    @Resource
    private SocketClientManager socketClientManager;

    @OnConnect
    public void onConnect(SocketIOClient client) {
        this.socketClientManager.saveSocketClient(client);
        System.out.println("客户端连接:" + getParamsFromClient(client));
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        this.socketClientManager.delSocketClient(client);
        System.out.println("客户端断开:" + getParamsFromClient(client));
    }

    @OnEvent("String")
    public void onEvent(SocketIOClient client, String message) {
        System.out.println("收到消息:" + message);
        this.socketClientManager.sendAll("testEvent", "刚刚发送了一条消息：" + message);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        start();
    }

    /**
     * 启动netty socket-io 服务
     */
    private void start() {
        socketIoServer.addPingListener(new HeartBeatHandler());
        Thread thread = new Thread(() -> socketIoServer.start());
        thread.start();
    }

    /**
     * 关闭netty socket-io 服务
     */
    @Override
    public void destroy() throws Exception {
        if (socketIoServer != null) {
            socketIoServer.stop();
        }
    }

    private String getParamsFromClient(SocketIOClient client) {

        HandshakeData data = client.getHandshakeData();
        String userId = data.getSingleUrlParam("userId");
        String clientType = data.getSingleUrlParam("clientType");
        String sessionId = client.getSessionId().toString();
        return "userId:" + userId + ",clientType:" + clientType + ",sessionId: " + sessionId;
    }
}
